package com.eportal.action.background;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.City;
import com.eportal.domain.Sysmenu;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TUsers;
import com.eportal.service.CityService;
import com.eportal.service.SysOptService;
import com.eportal.service.SysmenuService;
import com.eportal.service.TAgentService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TUsersService;
import com.eportal.util.Config;
import com.eportal.util.MD5;
import com.eportal.util.MdExpiringMap;
import com.eportal.util.VerifyCodeHelper;
import com.eportal.util.WebUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class CommonAction extends BaseAction implements ModelDriven<Sysopt> {
	
	
	private static Logger log = Logger.getLogger(CommonAction.class);
	
	/**
	 * 生成图片验证码
	 */
	public void genVerifyCode() {
		try {
			String func = getRequest().getParameter("func");
			String h = getRequest().getParameter("h");
			if(h==null){
				h="50";
			}
			String w = getRequest().getParameter("w");
			if(w==null){
				w="100";
			}
			VerifyCodeHelper.createCode(func, Integer.valueOf(w), Integer.valueOf(h), getRequest().getSession(), getResponse().getOutputStream());
		} catch (IOException e) {
			log.error(this, e);
		}
		
	}
    
	
	public void genQrImg(){
		
		try{
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//编码
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);//容错率
			hints.put(EncodeHintType.MARGIN, 0);
			String url = getRequest().getParameter("url");
			String w = getRequest().getParameter("w");
			String h = getRequest().getParameter("h");
			if(w==null){
				w="1024";
			}
			if(h==null){
				h="1024";
			}
			BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, Integer.valueOf(w), Integer.valueOf(h), hints);
			BufferedImage bufferImg = toBufferedImage(bitMatrix);
			ImageIO.write(bufferImg, "jpg", getResponse().getOutputStream());
		}catch(Exception e){
			log.error(this,e);
		}
		
	}
	
	public void downloadQrImg(){
		
		try{
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//编码
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);//容错率
			hints.put(EncodeHintType.MARGIN, 0);
			String url = getRequest().getParameter("url");
			String w = getRequest().getParameter("w");
			String h = getRequest().getParameter("h");
			String format = "jpg";
			if(w==null){
				w="1024";
			}
			if(h==null){
				h="1024";
			}
			BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, Integer.valueOf(w), Integer.valueOf(h), hints);
	
			BufferedImage image = toBufferedImage(bitMatrix);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ImageIO.write(image, format, out);
			HttpServletResponse response = getResponse();
			response.reset();
			// 设置response的Header
			// response.setContentType("application/vnd.ms-excel");
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + java.net.URLEncoder.encode("qrcode"+System.currentTimeMillis()+"." + format, "UTF-8"));
			// response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(out.toByteArray());
			toClient.flush();
			toClient.close();
			
		}catch(Exception e){
			log.error(this,e);
		}
		
	}
    
	private static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
    
    @Override
    public Sysopt getModel() {
        return user;
    }

    private Sysopt user = new Sysopt();

}
